package main

import (
	"context"
	"fmt"
	"log"

	"gogs.smarteye.com/servere/bvpublic/bvrpc"
	"gogs.smarteye.com/servere/bvrpcapi/api/bvapibase"
	"gogs.smarteye.com/servere/bvrpcapi/api/bvdialog"
	"gogs.smarteye.com/servere/gobvrtp/dialog"
	"gogs.smarteye.com/servere/utils/bvhelper"
	"gogs.smarteye.com/servere/utils/bvhelper/redisstruct"
)

type clientDialog struct {
	target        string
	appId, appKey string

	client *bvrpc.RPClient
	cli    bvdialog.BVDialogClient

	proto string
}

func NewClientDialog(tfkURL, discoAddr string, appId, appKey string, proto string) dialog.PullDialogInc {
	client := bvrpc.NewBuilder().WithAddr(tfkURL, discoAddr).Build()

	return &clientDialog{
		client: client,
		cli:    client.GetDialogClient(),
		appId:  appId,
		appKey: appKey,
		proto:  proto,
	}
}

func (tis *clientDialog) Open(ctx context.Context, puId string, channel int, offerSDP string) (dialogId string, answerSDP []byte, err error) {
	serviceToken, _ := tis.getServiceToken(tis.appId, tis.appKey)

	reply, err := tis.cli.OpenDialog(ctx, &bvdialog.OpenDialogRequest{
		RequesterType: redisstruct.NodeTypeService,
		Token:         serviceToken,
		TargetType:    redisstruct.NodeTypeUser,
		TargetId:      puId,
		ChannelIndex:  uint64(channel),
		Proto:         tis.proto,
		Sdp:           offerSDP,
		//RequesterAddr: "192.168.6.67",
		ServerAddr: "192.168.88.11",
	})
	if err != nil {
		return "", nil, err
	}

	if reply.GetCode() != bvapibase.ErrorCode_SUCCESS {
		return "", nil, fmt.Errorf("%v %v", reply.GetCode(), reply.GetMessage())
	}

	return reply.GetId(), []byte(reply.GetSdp()), nil
}

func (tis *clientDialog) Close(ctx context.Context, dialogId string) error {
	serviceToken, _ := tis.getServiceToken(tis.appId, tis.appKey)

	reply, err := tis.cli.CloseDialogs(ctx, &bvdialog.CloseDialogsRequest{
		Id:      []string{dialogId},
		Token:   serviceToken,
		InletID: "",
	})
	if err != nil {
		log.Println(err)
	} else {
		log.Println(reply.String())
	}

	return nil
}

func (tis *clientDialog) getServiceToken(appId, appKey string) (string, bool) {
	objectToken, err := bvhelper.NewServiceTokenInfo(appId, appKey, "cli")
	if err != nil {
		log.Println(err)
		return "", false
	}
	strToken, err := objectToken.String()
	if err != nil {
		log.Println(err)
		return "", false
	}

	return strToken, true
}
